﻿using mozhi.smarterp.Finance.Basedatas.Repository;
using System.Threading.Tasks;
using mozhi.smarterp.Finance.Basedatas;
using Volo.Abp;
using Volo.Abp.Guids;
using System;
using mozhi.smarterp.Finance.Enums;

namespace mozhi.smarterp.Finance
{
    public class CurrencyAppService : BaseDataAppService<Currency, CurrencyDto, CurrencyCreateDto, CurrencyUpdateDto>, ICurrencyAppService
    {
        public CurrencyAppService(IBaseDataRepository<Currency> repository, IGuidGenerator guidGenerator, IServiceProvider serviceProvider)
            : base(serviceProvider , ModuleCodeType.Currency)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
        }


        public override async Task<CurrencyDto> CreateAsync(CurrencyCreateDto dto)
        {
            await Validate(null, dto.Code, dto.Name);

            var currency = new Currency(_guidGenerator.Create(), dto.Code, dto.Name, dto.Symbol , dto.Activated);

            currency = await _repository.InsertAsync(currency);

            await _operationLogManager.LogAsync(ModuleCodeType.Currency, OperationType.Add, currency, null);

            return ObjectMapper.Map<Currency, CurrencyDto>(currency);
        }

        public override async Task<CurrencyDto> UpdateAsync(CurrencyUpdateDto dto)
        {
            var currency = await _repository.GetAsync(dto.Id);

            if (currency == null)
                throw new UserFriendlyException("货币不存在", "100000");

            var oldCurrency = ObjectMapper.Map<Currency, CurrencyDto>(currency);

            await Validate(dto.Id, dto.Code, dto.Name);

            currency.Change(dto.Code, dto.Name, dto.Symbol , dto.Activated);

            currency = await _repository.UpdateAsync(currency);

            var newCurrency = ObjectMapper.Map<Currency, CurrencyDto>(currency);

            await _operationLogManager.LogAsync(ModuleCodeType.Currency, OperationType.Update, oldCurrency, newCurrency);

            return newCurrency;
        }
    }
}
